package servlets;

import java.io.IOException;

import javaPersistence.Client;
import javaPersistence.Producto;
import javaPersistence.SaleService;
import javaPersistence.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.FormData;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public final String cookie_name = "GALLETICA";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user = "";
		String pass = "";
		response.setContentType("text/html");
		try {
			HttpSession sess = request.getSession();
			User usr = new User();
			
			if (request.getParameter("user") != null && request.getParameter("pass") != null) {
				user = request.getParameter("user");
				pass = request.getParameter("pass");
				//if (user.equals("Admin") && pass.equals("admin")) {
				if(usr.verifyUser(user, pass)){
					Cookie c = new Cookie(cookie_name, "");
					response.addCookie(c);
					sess.setAttribute("isLogin", "true");
					sess.setAttribute("userCode", usr.obtainUser(user));
					sess.setMaxInactiveInterval(60);
					
					sess.setAttribute("title", "MENU");
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/postIndex.jsp");
				} else {
					response.sendRedirect(request.getContextPath() + "/jsps/error.jsp");
				}
			} else if(request.getParameter("command") != null && !request.getParameter("command").equals("salir")){
				if(request.getParameter("command").equals("user"))
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/usuarios.jsp");
				if(request.getParameter("command").equals("client")){
					FormData fdata = new FormData();
					Client client = new Client();
					fdata.setClients(client.loadAllClient());
					sess.setAttribute("FormData", fdata);
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/clientes.jsp");
				}
				if(request.getParameter("command").equals("product")){
					FormData fdata = new FormData();
					Producto product = new Producto();
					fdata.setServices(product.loadAllServices());
					sess.setAttribute("FormData", fdata);
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/productos.jsp");
				}
				if(request.getParameter("command").equals("sale")){
					FormData fdata = new FormData();
					Client client = new Client();
					Producto product = new Producto();
					SaleService saleServ = new SaleService();
					fdata.setClients(client.loadAllClient());
					fdata.setServices(product.loadAllServices());
					fdata.setSaleServices(saleServ.loadAllDataSalesServices());
					sess.setAttribute("FormData", fdata);
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/ventas.jsp");
				}
				if(request.getParameter("command").equals("sql"))
					response.sendRedirect(request.getContextPath() + "/jsps/negocio/sqlDDL.jsp");
				//galleta(request, response, request.getParameter("command"));
				//response.sendRedirect(request.getContextPath() + "/jsps/negocio/postIndex.jsp");
			} else if(request.getParameter("command") != null && request.getParameter("command").equals("salir")){ 
				deleteCookie(request, response);
				sess.invalidate();
				response.sendRedirect(request.getContextPath()+"/");
			} else {
				response.sendRedirect(request.getContextPath() + "/jsps/error.jsp");
			}

		} catch (Exception e) {
		}
	}

	/*public String menu(HttpServletRequest request, String title) {
		StringBuilder str = new StringBuilder();
		str.append("<html><head><title>::: BIENVENIDO A ").append(title).append(" :::</title>");
		str.append("<link rel=\"stylesheet\" href=\"").append(request.getContextPath()).append("/recurso/style.css\">");
		str.append("</head>");
		str.append("<body><h1> Actualmente usted se encuentra en \"").append(title).append("\"</h1> <p>Elija Una Opcion del Menu</p>");
		str.append("<ul class=\"navbar\">");
		str.append("<li><a href=\"").append(request.getContextPath()).append("/Action.jsp\"> Opcion1 </a></li>");
		str.append("<li><a href=\"").append(request.getContextPath()).append("/Action1.jsp\"> Opcion2 </a></li>");
		str.append("<li><a href=\"").append(request.getContextPath()).append("/Action2.jsp\"> Opcion3 </a></li>");
		str.append("</ul>");
		str.append("<p>");
		str.append("Los Valores contenidos en la cookie son:</br>");

		str.append("</p>");
		str.append("<form action=\"").append(request.getContextPath())
				.append("/Action.jsp\" method=\"post\">");
		str.append("<input type=\"submit\" value=\"Salir\" class=\"boton\">");
		str.append("</form>");
		str.append("</body></html>");
		return str.toString();
	}*/

	public void createCookie(HttpServletResponse response, Cookie cookie,
			String accion) {
		StringBuilder valor = new StringBuilder(cookie.getValue());
		valor.append(accion);
		cookie.setMaxAge(0);
		Cookie c = new Cookie(cookie_name, valor.toString());
		response.addCookie(c);
	}

	public void deleteCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(cookie_name)) {
					cookies[i].setMaxAge(0);
					Cookie c = new Cookie(cookie_name, "");
					response.addCookie(c);
				}
			}
		}
	}
	
	
	public void galleta(HttpServletRequest request, HttpServletResponse response, String accion) throws IOException{
		HttpSession sess = request.getSession();
        String isLogin = (String)sess.getAttribute("isLogin");
		if(sess != null && isLogin != null && isLogin.equals("true")){
			sess.setAttribute("title", accion);
            Cookie[] cookies = request.getCookies();
            if (cookies != null){
                for(int i=0; i<cookies.length; i++) {
                    if (cookies[i].getName().equals(cookie_name)){
                    	createCookie(response, cookies[i], accion+",");
                    }
                }
            }
        }else{
        	deleteCookie(request, response);
        	response.sendRedirect(request.getContextPath()+"/");
        }
		
	}

}
